import torch
import torch.nn.functional as F

batch_size = 1
image_height = 1024
image_width = 768
num_channels = 3

# 生成随机的图像数据和对应的标签数据
images1 = torch.randn(batch_size, num_channels, image_height, image_width)
images2 = images1.view(batch_size, image_height, image_width, num_channels).view(batch_size, num_channels, image_height,
                                                                                 image_width)
images5 = images1.permute(0, 2, 3, 1).contiguous().permute(0, 3, 1, 2).contiguous()
images6 = images1.permute(0, 2, 3, 1).permute(0, 3, 1, 2)
print(torch.equal(images1, images5))
print(torch.equal(images1, images6))

images3 = images1.view(batch_size, image_height, image_width, num_channels).permute(0, 3, 1, 2)
print(torch.equal(images1, images2))
print(torch.equal(images2, images3))
images4 = images1.permute(0, 2, 3, 1).contiguous().view(batch_size, num_channels, image_height,
                                                        image_width)
print(torch.equal(images1, images3))
print(torch.equal(images3, images4))

# permute(0, 2, 1, 3).contiguous()

labels = torch.randint(0, 1, (batch_size, image_height, image_width))
# 定义交叉熵损失函数
criterion = torch.nn.CrossEntropyLoss()
print(images1.shape, labels.shape)

loss = criterion(images1, labels)
print(images1)
print(labels)
# 打印损失值
print(loss.item())

a = torch.FloatTensor(
    [[[[0.0, 1.0, 1.0],
       [0.0, 1.0, 1.0],
       [0.0, 0.0, 0.0]],

      [[0.0, 1.0, 1.0],
       [0.0, 1.0, 1.0],
       [0.0, 0.0, 0.0]],

      [[0.0, 1.0, 1.0],
       [0.0, 1.0, 1.0],
       [0.0, 0.0, 0.0]]]]
)

a = torch.FloatTensor(
    [[[0.0, 100.0, 100.0],
      [0.0, 100.0, 100.0],
      [0.0, 0.0, 0.0]],

     [[0.0, 100.0, 100.0],
      [0.0, 100.0, 100.0],
      [0.0, 0.0, 0.0]],

     [[0.0, 100.0, 100.0],
      [0.0, 100.0, 100.0],
      [0.0, 0.0, 0.0]]]
)
labels = torch.LongTensor(
    [[0, 1, 1],
     [0, 1, 1],
     [0, 0, 0]]
)
print(a.shape, labels.shape)
print(criterion(a, labels))

c = torch.randn([2, 3, 128, 96])
d = torch.randint(0, 1, (2, 128, 96))
print(criterion(c, d))

import torch

# 定义第一个图像
image1 = torch.randn(1, 1, 1024, 768)
image1_sigmoid = torch.sigmoid(image1)
# 定义第二个图像
image2 = torch.zeros(1, 1, 1024, 768)
image2[:, :, 200:400, 300:500] = 1
# 将第一个图像经过sigmoid函数处理

print(image2.dtype)
# 计算损失函数
loss_fn = torch.nn.BCELoss()
loss = loss_fn(image1_sigmoid, image2)
print(loss)
